package com.kinghunt.misp.service.impl.userx;

import com.alibaba.fastjson.JSON;
import com.kinghunt.misp.common.constant.SystemConstant;
import com.kinghunt.misp.common.dto.userx.OrganizationDTO;
import com.kinghunt.misp.common.dto.userx.RoleDTO;
import com.kinghunt.misp.common.dto.userx.UserDTO;
import com.kinghunt.misp.common.enums.userx.RoleEnum;
import com.kinghunt.misp.common.utils.HttpServletRequestUtil;
import com.kinghunt.misp.dal.dao.configx.ConfigValueDAO;
import com.kinghunt.misp.dal.dao.userx.OrganizationDAO;
import com.kinghunt.misp.dal.dao.userx.UserDAO;
import com.kinghunt.misp.dal.model.configx.ConfigValueDO;
import com.kinghunt.misp.dal.model.userx.OrganizationDO;
import com.kinghunt.misp.dal.model.userx.UserDO;
import com.kinghunt.misp.service.api.userx.AutoLoginService;
import com.bygoodtech.kings.base.utils.ConvertUtil;
import com.bygoodtech.kings.common.dto.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

@Slf4j
@Service
public class AutoLoginServiceImpl implements AutoLoginService {
    @Autowired
    private UserDAO userDao;
    @Autowired
    private OrganizationDAO organizationDAO;
    @Autowired
    ConfigValueDAO configValueDAO;

    @Override
    public ApiResult<UserDTO> loginByIp(HttpServletRequest request) {
        String clientIp = HttpServletRequestUtil.getClientIp(request);
        if (StringUtils.isBlank(clientIp)) {
            return ApiResult.ok(null);
        }
        log.info("login by IP : {}", clientIp);

        Map<Long, List<String>> ipSegmentMap = getIpLoginSegmentMap();
        if (Objects.isNull(ipSegmentMap) || ipSegmentMap.isEmpty()) {
            return ApiResult.ok(null);
        }

        Long currentOrgId = null;
        // 比对IP，判断当前IP属于哪个机构的网段
        for (Long orgId : ipSegmentMap.keySet()) {
            List<String> ipSegments = ipSegmentMap.get(orgId);
            for (String ipSegment : ipSegments) {
                if (isIpAddressInSubnet(clientIp, ipSegment)) {
                    currentOrgId = orgId;
                    break;
                }
            }
        }

        if (Objects.isNull(currentOrgId))
            return ApiResult.ok(null);

        // 取特定角色用户
        List<UserDO> userDOs = userDao.selectByOrgIAndRoleId(currentOrgId, RoleEnum.ORG_IP.getId());
        if (CollectionUtils.isNotEmpty(userDOs)) {
            UserDTO user = ConvertUtil.convert(userDOs.get(0), UserDTO.class);

            OrganizationDO orgDO = organizationDAO.selectByPrimaryKey(currentOrgId);
            OrganizationDTO organizationDTO = ConvertUtil.convert(orgDO, OrganizationDTO.class);
            user.setOrganization(organizationDTO);

            user.setRoleId(RoleEnum.ORG_IP.getId());
            user.setRoleName(RoleEnum.ORG_IP.getName());
            user.setRoles(Arrays.asList(new RoleDTO(RoleEnum.ORG_IP.getId(),
                    RoleEnum.ORG_IP.getCode(),
                    RoleEnum.ORG_IP.getName(),
                    RoleEnum.ORG_IP.getName(),
                    SystemConstant.SYSTEM_CODE,
                    false,
                    null)));
            log.info("login by IP : {}, orgId : {}", clientIp, currentOrgId);
            return ApiResult.ok(user);
        }
        return ApiResult.ok(null);
    }

    /**
     * 获取所有允许IP免登录机构的IP网段配置
     *
     * @return
     */
    private Map<Long, List<String>> getIpLoginSegmentMap() {
        Map<Long, List<String>> ipSegmentMap = new HashMap<>();
        List<Long> orgIds = configValueDAO.selectOrgIdByIpLoginSwitchOn();
        if (CollectionUtils.isEmpty(orgIds)) {
            return null;
        }
        List<ConfigValueDO> configs = configValueDAO.selectIpLoginSegmentByOrgIds(orgIds);
        if (CollectionUtils.isEmpty(configs)) {
            return null;
        }

        for (ConfigValueDO config : configs) {
            if (StringUtils.isBlank(config.getValue()))
                continue;
            List<String> ipSegments = JSON.parseObject(config.getValue(), List.class);
            ipSegmentMap.put(config.getOrgId(), ipSegments);
        }
        return ipSegmentMap;
    }

    /**
     * 判断IP是否在该网段中
     *
     * @param ipAddress
     * @param subnetAddress 子网地址
     * @param subnetMask 子网掩码
     */
    private static boolean isIpAddressInSubnet(String ipAddress, String subnetAddress, String subnetMask) throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getByName(ipAddress);
        InetAddress subnet = InetAddress.getByName(subnetAddress);
        InetAddress mask = InetAddress.getByName(subnetMask);

        byte[] inetAddressBytes = inetAddress.getAddress();
        byte[] subnetBytes = subnet.getAddress();
        byte[] maskBytes = mask.getAddress();

        for (int i = 0; i < inetAddressBytes.length; i++) {
            int addressByte = inetAddressBytes[i] & 0xFF;
            int subnetByte = subnetBytes[i] & 0xFF;
            int maskByte = maskBytes[i] & 0xFF;

            if ((addressByte & maskByte) != (subnetByte & maskByte)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 子网掩码转换
     *
     * @param prefixLength
     * @return
     */
    private static String subnetMaskFromPrefixLength(int prefixLength) {
        if (prefixLength < 0 || prefixLength > 32) {
            throw new IllegalArgumentException("Invalid prefix length");
        }

        int mask = 0xffffffff << (32 - prefixLength);
        return String.format("%d.%d.%d.%d",
                (mask & 0xff000000) >>> 24,
                (mask & 0x00ff0000) >>> 16,
                (mask & 0x0000ff00) >>> 8,
                (mask & 0x000000ff));
    }

    /**
     * 判断IP是否在该网段中
     *
     * @param subnetRange 子网范围 x.x.x.x/xx 形式
     */
    private static boolean isIpAddressInSubnet(String ipAddress, String subnetRange) {
        String[] networkips = ipAddress.split("\\.");
        int ipAddr = (Integer.parseInt(networkips[0]) << 24)
                | (Integer.parseInt(networkips[1]) << 16)
                | (Integer.parseInt(networkips[2]) << 8)
                | Integer.parseInt(networkips[3]);

        // 拿到主机数
        int type = Integer.parseInt(subnetRange.replaceAll(".*/", ""));
        int ipCount = 0xFFFFFFFF << (32 - type);

        String maskIp = subnetRange.replaceAll("/.*", "");
        String[] maskIps = maskIp.split("\\.");

        int cidrIpAddr = (Integer.parseInt(maskIps[0]) << 24)
                | (Integer.parseInt(maskIps[1]) << 16)
                | (Integer.parseInt(maskIps[2]) << 8)
                | Integer.parseInt(maskIps[3]);

        return (ipAddr & ipCount) == (cidrIpAddr & ipCount);
    }
}
